package com.qianyucc.blog.controller.comm;

import com.qianyucc.blog.exception.*;
import com.qianyucc.blog.model.dto.*;
import com.qianyucc.blog.model.entity.*;
import com.qianyucc.blog.model.enums.*;
import com.qianyucc.blog.model.vo.*;
import com.qianyucc.blog.provider.*;
import com.qianyucc.blog.mapper.*;
import com.qianyucc.blog.service.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.*;
import me.zhyd.oauth.model.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;
import javax.validation.constraints.*;
import java.util.*;

/**
 * @author lijing
 * @date 2019-10-11 15:29
 * @description 用户相关api
 */
@Controller("commUserController")
@RequestMapping("/comm/user")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GiteeProvider giteeProvider;
    @Autowired
    private UserService userService;
    @Autowired
    private QQProvider qqProvider;
    @Value("${blog.client}")
    private String clientUrl;

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    @ResponseBody
    public UserVO getUserInfo(@ApiParam("用户登录态标识") @NotNull(message = "token不能为空") String token) {
        UserDO userDO = userMapper.findByToken(token);
        if (userDO != null) {
            UserVO userVO = UserVO.create(userDO);
            return userVO;
        }
        throw new TokenExpiredException();
    }

    @ApiOperation("用户登录，返回用户登录地址")
    @GetMapping("/login")
    @ResponseBody
    public ResultVO login(@ApiParam("用户登录类型") String type) {
        if (LoginType.QQ.getType().equals(type)) {
            return ResultVO.ok(qqProvider.getLoginUrl());
        } else if (LoginType.GITEE.getType().equals(type)) {
            return ResultVO.ok(giteeProvider.getLoginUrl());
        } else {
            throw new InvalidLoginTypeException();
        }
    }

    @ApiOperation("用户使用码云登录的回调地址")
    @GetMapping("/gitee/callback")
    public void giteeCallback(AuthCallback callback, HttpServletResponse res) {
        GiteeUserDTO userDTO = giteeProvider.getUserInfo(callback);
        log.info(userDTO.toString());
        String token = UUID.randomUUID().toString();
        // 登录之后生成token
        userService.giteeLogin(userDTO, token);
        res.setStatus(302);
        res.setHeader("location", clientUrl + "?token=" + token);
    }

    @ApiOperation("用户使用QQ登录的回调地址")
    @GetMapping("/qq/callback")
    public void qqCallback(AuthCallback callback, HttpServletResponse res) {
        QQUserDTO userDTO = qqProvider.getUserInfo(callback);
        //log.info(userDTO.toString());
        String token = UUID.randomUUID().toString();
        // 登录之后生成token
        userService.qqLogin(userDTO, token);
        res.setStatus(302);
        res.setHeader("location", clientUrl + "?token=" + token);
    }
}